package com.oly.cms.hand.security.service;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.oly.cms.general.manager.WebAsyncManager;
import com.oly.cms.hand.manager.factory.HandAsyncFactory;
import com.oly.cms.hand.security.context.AuthenticationContextHolder;
import com.grace.common.constant.CacheConstants;
import com.grace.common.constant.Constants;
import com.grace.common.core.domain.entity.SysUser;
import com.grace.common.utils.MessageUtils;
import com.grace.common.utils.SecurityUtils;
import com.grace.redis.utils.RedisCache;

/**
 * 登录密码方法
 * 
 * @author grace
 */
@Component
public class WebPasswordService {
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     * 
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        if (usernamePasswordAuthenticationToken != null) {
            String username = usernamePasswordAuthenticationToken.getName();
            String password = usernamePasswordAuthenticationToken.getCredentials().toString();
            Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

            if (retryCount == null) {
                retryCount = 0;
            }

            if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
                WebAsyncManager.me().execute(HandAsyncFactory.recordLogininfor(username, "admin", Constants.LOGIN_FAIL,
                        MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
                throw new LockedException("账户被锁定异常");
            }

            if (!matches(user, password)) {
                retryCount = retryCount + 1;
                WebAsyncManager.me().execute(HandAsyncFactory.recordLogininfor(username, "admin", Constants.LOGIN_FAIL,
                        MessageUtils.message("user.password.retry.limit.count", retryCount)));
                redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
                throw new UsernameNotFoundException("账户名/或密码错误");
            } else {
                clearLoginRecordCache(username);
            }

        }
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }

}
